<template>
  <div>
    <!--
        action：上传地址
        show-file-list：是否显示已上传文件列表
        on-success：上传成功的回调
        before-upload：上传之前的回调
    -->
    <!-- 配置不满足业务需求，需要自定以
         添加 http-request: 实现自定义上传逻辑
    -->
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="httpRequestFn"
    >
      <!-- 上传成功后预览的图片 -->
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <!-- 上传图片中间的 + 号 -->
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="progressShow" type="circle" :percentage="percentage" status="success" class="progress" />

    </el-upload>
  </div>
</template>

<script>
// 导入 cos 模块
const COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
const cos = new COS({
  SecretId: 'AKIDoRothFWWFgqjLgkX3HFwLUMxHK7dsrYz',
  SecretKey: 'A4g39yVR7WeV6PRChuqVt1rQijTw84i5'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      progressShow: false,
      percentage: 0
    }
  },
  methods: {
    httpRequestFn(files) {
      console.log(files)
      if (files.file) {
        this.progressShow = true
        cos.putObject({
          Bucket: 'fjq-1308109357', // 存储桶的名称，必须
          Region: 'ap-nanjing', // 存储桶所在地域，必须字段
          Key: files.file.name, // 文件名，必须
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: files.file, // 上传文件对象
          // 上传进度条
          onProgress: (progressData) => {
            this.percentage = parseInt(progressData.percent * 100)
          }
        }, (err, data) => {
          if (err === null && data.statusCode === 200) {
            this.imageUrl = `https://${data.Location}`
            this.$emit('getImgUrl', this.imageUrl)
          }
          this.progressShow = false
        })
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>
